<template>
  <div class="container">
    <navigate>编辑精神状态</navigate>
    <div class="title flex_align_center flex_row">
      <div class="bar"></div>
      <div class="text">精神状态概况</div>
    </div>

    <div class="card_mental_state">
      <template v-for="(item, i) in list">
        <van-cell-group v-if="item.opition_type == 1" class="nowrap input_outer father_relative">
          <van-field readonly clickable v-model="item.val.name" :label="item.name" placeholder="请选择"
            @click="item.visible = true" />
          <v-picker :columns="item.templateOptions" valueKey="name" @confirm="
            item.val = $event;
          item.visible = false;
          " :isVisible="item.visible" @cancel="item.visible = false" />
          <img src="@/assets/images/common/right.png" class="right vertical_center" alt="" />
        </van-cell-group>

        <van-cell-group :key="i + '-++'" class="input_outer" v-else-if="item.opition_type == 2">
          <van-field v-model="item.val" :label="item.name" placeholder="请输入" />
        </van-cell-group>
      </template>
    </div>

    <div class="title flex_align_center flex_row">
      <div class="bar"></div>
      <div class="text">精神情况记录</div>
    </div>
    <div class="card_questionnaire">
      <div class="item" v-for="(item, index) in list2" :key="index">
        <div :class="['question', { type2: item.opition_type == 2 }]">
          {{ item.name }}
        </div>
        <textarea placeholder="请输入实际情况" class="textarea" v-model="item.val" v-if="item.opition_type == 2"></textarea>
        <template v-else>
          <v-radio class="type2" v-for="(e, i) in item.templateOptions" :key="i" @selected="item.val.id = $event"
            :val="e.id" v-model="item.val.id" :idText="'text' + i + index" :name="`name${index}`"
            :text="e.name"></v-radio>
        </template>
      </div>
    </div>
    <button class="btn" @click="save">保存资料</button>
  </div>
</template>

<script>
import { getTemplateList, submitSelfAssessment, queryArchivesResults } from '@/api/funcation/selfAssessment'
import { mapState } from "vuex";
export default {
  data() {
    return {
      list: [],
      list2: [],
      userArchivesResults: [] // 新增：存储接口返回数据（响应式）
    };
  },
  computed: {
    ...mapState(["INFO"]),
  },
  async created() {
    await this.getTemplateList();
    await this.getArchivesResults();
  },
  methods: {
    async getTemplateList() {
      const { data } = await getTemplateList({ id: 7 });
      this.list = data[0].templates[0].children || [];
      this.list2 = data[0].templates[1].children || [];

      // 初始化 list（精神状态概况）
      this.list.forEach(item => {
        this.$set(item, "visible", false);
        this.$set(item, "val", item.opition_type === 1 ? {} : "");
      });

      // 初始化 list2（精神情况记录）
      this.list2.forEach(item => {
        this.$set(item, "visible", false);
        this.$set(item, "val", item.opition_type === 1 ? { id: "" } : "");
      });
    },
    async getArchivesResults() {
      const par = {
        user_id: this.INFO.id,
        type_id: 7,
      };
      const res = await queryArchivesResults(par);
      if (res.code === 200 && res.data[0]?.content) {
        try {
          this.userArchivesResults = JSON.parse(res.data[0].content);
          const combinedList = [...this.list, ...this.list2];

          this.userArchivesResults.forEach(({ questionId, answersId }) => {
            const item = combinedList.find(item => item.id === Number(questionId));
            if (!item || answersId === undefined) return;

            if (item.opition_type === 1) {
              const option = item.templateOptions.find(opt => opt.id === answersId);
              if (option) {
                if (this.list.includes(item)) {
                  this.$set(item, "val", option); // 下拉框赋值完整对象
                } else {
                  this.$set(item.val, "id", option.id); // 单选框仅赋值id
                }
              }
            } else if (item.opition_type === 2) {
              this.$set(item, "val", answersId); // 文本域直接赋值
            }
          });
        } catch (e) {
          console.error("回显失败:", e);
        }
      }
    },
    async save() {
      const idPairs = [
        ...this.list.map(item => ({
          questionId: item.id,
          answersId: item.opition_type === 1 ? item.val?.id : item.val
        })),
        ...this.list2.map(item => ({
          questionId: item.id,
          answersId: item.opition_type === 1 ? item.val?.id : item.val
        }))
      ];

      const params = {
        user_id: this.INFO.id,
        content: JSON.stringify(idPairs),
        type_id: 7,
        source: 1,
      };

      const res = await submitSelfAssessment(params);
      if (res.code === 200) {
        this.$toast.success("修改成功！");
      }
    },
  },
};
</script>


<style lang="less" scoped>
@import "./css/index.less";
@import "../styles/common.less";
</style>